package ordersSpu

import (
	"context"
	"github.com/google/uuid"
	"github.com/kuangshp/go-utils/k"
	"github.com/shopspring/decimal"
	"insighttracking/apps/sorting/auth"
	"insighttracking/query/model"
	"insighttracking/query/service"
	"net/http"

	"insighttracking/apps/sorting/internal/svc"
	"insighttracking/apps/sorting/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
	"os"
)

type GetOrdersSpuDetailApiLogic struct {
	logx.Logger
	ctx     context.Context
	svcCtx  *svc.ServiceContext
	Request *http.Request
}

func NewGetOrdersSpuDetailApiLogic(ctx context.Context, svcCtx *svc.ServiceContext, request *http.Request) *GetOrdersSpuDetailApiLogic {
	hostname, _ := os.Hostname()
	return &GetOrdersSpuDetailApiLogic{
		Logger: logx.WithContext(ctx).WithCallerSkip(0).WithFields(
			logx.Field("Log_UUID", uuid.New().String()),
			logx.Field("hostname", hostname)),
		ctx:     ctx,
		svcCtx:  svcCtx,
		Request: request,
	}
}

func (l *GetOrdersSpuDetailApiLogic) GetOrdersSpuDetailApi(req *types.GetOrdersSpuDetailReq) (resp []types.GetOrdersSpuDetailResp, err error) {
	accountInfo, err := auth.GetAccountInfo(l.svcCtx, l.Request)
	if err != nil {
		return nil, err
	}
	resp = make([]types.GetOrdersSpuDetailResp, 0)
	ordersEntities, err := service.OrdersService.GetSendGoodsDateListApi(l.ctx, accountInfo.EnterpriseId, req.StartDate, req.EndDate, "")
	if err != nil || len(ordersEntities) == 0 {
		return make([]types.GetOrdersSpuDetailResp, 0), nil
	}
	orderIdList := k.Map(ordersEntities, func(item *model.OrdersEntity, index int) int64 {
		return item.ID
	})

	totalMap, err := service.OrdersDetailService.GetTotalSpuApi(l.ctx, orderIdList)
	if err != nil {
		return nil, err
	}

	for spuID, item := range totalMap {
		// 没有对应的SPU，直接跳过
		if spuID != req.SpuId {
			continue
		}
		orderIDs := item.OrderIDs
		for _, orderID := range orderIDs {
			singleMap, _ := service.OrdersDetailService.GetTotalSpuApi(l.ctx, []int64{orderID})
			// 查询是否有分拣记录
			storeSortingDetails, err := service.StoreSortingDetailService.GetStoreSortingDetailBySpuIDApi(l.ctx, orderID, spuID)
			if err != nil {
				return resp, err
			}
			ordersEntity, err := service.OrdersService.GetByIdApi(l.ctx, orderID)
			if err != nil {
				return resp, err
			}
			customerName, err := service.EnterpriseCustomerService.GetNameByIdApi(l.ctx, ordersEntity.CustomerID)
			if err != nil {
				return resp, err
			}
			if len(storeSortingDetails) == 0 {
				resp = append(resp, types.GetOrdersSpuDetailResp{
					OrdersId:        orderID, // 订单id
					OrdersDetailsId: spuID,
					SpuID:           spuID,
					CustomerID:      ordersEntity.CustomerID,               // 客户id,关联到enterprise_customer表主键id
					CustomerName:    customerName,                          // 门店名称
					TotalCount:      singleMap[spuID].Count.StringFixed(2), // 订单商品数量
					SortingCount:    "0",                                   // 已经分拣的重量
					Status:          0,                                     // 状态0表示待分拣，10表示已分拣，20表示已出库
				})
			} else {
				sortingCount := decimal.Zero
				for _, item1 := range storeSortingDetails {
					sortingCount = sortingCount.Add(item1.OutboundCount)
				}
				resp = append(resp, types.GetOrdersSpuDetailResp{
					OrdersId:        orderID, // 订单id
					OrdersDetailsId: spuID,
					SpuID:           spuID,                                 // 订单详情id
					CustomerID:      ordersEntity.CustomerID,               // 客户id,关联到enterprise_customer表主键id
					CustomerName:    customerName,                          // 门店名称
					TotalCount:      singleMap[spuID].Count.StringFixed(2), // 订单商品数量
					SortingCount:    sortingCount.StringFixed(2),           // 已经分拣的重量
					Status:          10,                                    // 状态0表示待分拣，10表示已分拣，20表示已出库
				})
			}
		}
	}
	return resp, nil

	/* 之前的逻辑
	detailEntities, err := service.OrdersDetailService.GetOrderDetailBySpuIdApi(l.ctx, req.SpuId, orderIdList)
	if err != nil || len(detailEntities) == 0 {
		return
	}
	logx.WithContext(l.ctx).Infof("订单详情id:%v", orderIdList)
	// 查询已经分拣的重量
	var result = make([]types.GetOrdersSpuDetailResp, 0)
	for _, item := range detailEntities {
		ordersEntity, err := service.OrdersService.GetDetailByIdApi(l.ctx, item.OrdersID)
		if err != nil {
			continue
		}
		// 根据订单详情id和商品id查询已经分拣的
		storeSortingDetailEntity, err := service.StoreSortingDetailService.GetStoreSortingDetailByOrdersDetailListApi(l.ctx, []int64{item.ID})
		var status int64
		if err == nil && len(storeSortingDetailEntity) > 0 {
			status = 10
		}
		// 查询是否有出库记录
		sendGoodsRecordEntity, err2 := service.SendGoodsRecordService.GetStoreSortingByOrderIdApi(l.ctx, item.OrdersID)
		if !errors.Is(err2, gorm.ErrRecordNotFound) {
			_, err = service.SendGoodsRecordDetailService.GetSendGoodsRecordDetailBySpuIdApi(l.ctx, sendGoodsRecordEntity.ID, item.SpuID)
			l.Logger.Infof("当前出库记录:%+v", sendGoodsRecordEntity)
			if !errors.Is(err, gorm.ErrRecordNotFound) {
				status = 20
			}
		}

		logx.WithContext(l.ctx).Infof("查询已经分拣的数据:%v", k.MapToString(storeSortingDetailEntity))
		if err != nil || len(storeSortingDetailEntity) == 0 {
			result = append(result, types.GetOrdersSpuDetailResp{
				OrdersId:        item.OrdersID,                // 订单id
				OrdersDetailsId: item.ID,                      // 订单详情id
				CustomerID:      ordersEntity.CustomerID,      // 客户id,关联到enterprise_customer表主键id
				CustomerName:    ordersEntity.CustomerName,    // 门店名称
				TotalCount:      item.SpuCount.StringFixed(2), // 订单商品数量
				SortingCount:    "0",                          // 已经分拣的重量
				Status:          status,                       // 状态0表示待分拣，10表示已分拣，20表示已出库
			})
		} else {
			sortingCount := decimal.Zero
			for _, item1 := range storeSortingDetailEntity {
				sortingCount = sortingCount.Add(item1.OutboundCount)
			}
			result = append(result, types.GetOrdersSpuDetailResp{
				OrdersId:        item.OrdersID,                // 订单id
				OrdersDetailsId: item.ID,                      // 订单详情id
				CustomerID:      ordersEntity.CustomerID,      // 客户id,关联到enterprise_customer表主键id
				CustomerName:    ordersEntity.CustomerName,    // 门店名称
				TotalCount:      item.SpuCount.StringFixed(2), // 订单商品数量
				SortingCount:    sortingCount.StringFixed(2),  // 已经分拣的重量
				Status:          status,                       // 状态0表示待分拣，10表示已分拣，20表示已出库
			})
		}
	}
	*/
}
